<template>
  <div class="login">
    <div class="plus"></div>
    <van-nav-bar>
      <template #left>
        <div class="left-nav">
          <div class="logo">
            <img class="auto-img" src="../assets/images/logo.png" alt="" />
          </div>
          <div class="logo-title">咖啡商城</div>
        </div>
      </template>
      <template #right>
        <div class="right-title" @click="goHome">先逛一逛</div>
      </template>
    </van-nav-bar>
    <div class="login-box">
      <!-- 找回密码 -->
      <div class="login-info" v-if="isfindPassword">
        <div class="login-title">
          <div class="welcome">找回密码！</div>
          <div class="en-welcome">Find password</div>
        </div>
        <div class="login-form">
          <van-form>
            <div class="inp-box" v-if="findPasswordInfo.setPassword">
              <van-field v-model="findPasswordInfo.phone" name="手机号" label="手机号" placeholder="请输入手机号" autocomplete="off" />
              <van-field v-model="findPasswordInfo.password" :type="loginPasswordStatus ? 'password' : 'text'" name="新密码" label="新密码" placeholder="请输入新密码" :right-icon="loginPasswordStatus ? 'closed-eye' : 'eye-o'" autocomplete="off" @click-right-icon="togglePassword('loginPasswordStatus')" />
            </div>
            <div class="inp-box" v-else>
              <van-field v-model="findPasswordInfo.email" name="邮箱" label="邮箱" placeholder="请输入邮箱" autocomplete="off" />
              <van-field v-model="findPasswordInfo.code" name="验证码" label="验证码" placeholder="请输入验证码" autocomplete="off">
                <template #button v-if="isfindPassword">
                  <van-button size="small" type="primary" @click="sendCode">
                    <span v-if="codeStatus">发送验证码</span>
                    <div class="codeTime" v-else>
                      <van-count-down :time="time" format="ss" @finish="resetTime" />
                      <!-- <span>后重新发送</span> -->
                    </div>
                  </van-button>
                </template>
              </van-field>
            </div>
            <div class="forgot">
              <div class="forgot-text" @click="toggleView(false)">已有账号，立即登录</div>
            </div>
            <div class="login-btn">
              <van-button v-if="findPasswordInfo.setPassword" round block color="#ff594d" native-type="submit" @click="resetPassword">下一步</van-button>
              <van-button v-else round block color="#ff594d" native-type="submit" @click="checkCode">下一步</van-button>
            </div>
            <div class="login-btn" v-if="findPasswordInfo.setPassword">
              <van-button round block @click="goLogin">返&nbsp;&nbsp;回</van-button>
            </div>
          </van-form>
        </div>
      </div>
      <!-- 登录注册 -->
      <div class="login-info" v-else>
        <div class="login-title">
          <div class="welcome">欢迎回来！</div>
          <div class="en-welcome">Please login to your account</div>
        </div>
        <div class="login-form">
          <van-form>
            <div class="inp-box">
              <van-field v-model="loginUserInfo.phone" name="手机号" label="手机号" placeholder="请输入手机号" autocomplete="off" />
              <van-field v-model="loginUserInfo.password" :type="loginPasswordStatus ? 'password' : 'text'" name="密码" label="密码" placeholder="请输入密码" :right-icon="loginPasswordStatus ? 'closed-eye' : 'eye-o'" autocomplete="off" @click-right-icon="togglePassword('loginPasswordStatus')" />
            </div>
            <div class="forgot">
              <div class="forgot-text" @click="toggleView(true)">忘记密码？</div>
            </div>
            <div class="login-btn">
              <van-button round block color="#ff594d" native-type="submit" @click="login">登&nbsp;&nbsp;录</van-button>
            </div>
            <div class="login-btn">
              <van-button round block @click="showPopup">注&nbsp;&nbsp;册</van-button>
            </div>
          </van-form>
        </div>
      </div>
    </div>
    <van-popup v-model="show" position="bottom" closeable>
      <div class="register">
        <div class="register-title">注册</div>
        <div class="reg-form">
          <van-form @submit="register">
            <van-field v-model="regUserInfo.phone" name="手机号" label="手机号" placeholder="11位手机号" autocomplete="off" />
            <van-field v-model="regUserInfo.password" :type="passwordStatus ? 'password' : 'text'" name="密码" label="密码" placeholder="8-16位字母数字组合密码" :right-icon="passwordStatus ? 'closed-eye' : 'eye-o'" autocomplete="off" @click-right-icon="toggleRegPassword" />
            <van-field v-model="regUserInfo.nickName" type="text" name="昵称" label="昵称" placeholder="1-10位昵称" autocomplete="off" />
            <div class="login-btn">
              <van-button round block color="#ff594d" native-type="submit">注&nbsp;&nbsp;册</van-button>
            </div>
          </van-form>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
export default {
  name: "Login",

  data() {
    return {
      //是否显示弹出层
      show: false,
      //用户登录信息
      loginUserInfo: {
        phone: "",
        password: "",
      },
      //注册用户信息
      regUserInfo: {
        phone: "",
        password: "",
        nickName: "",
      },
      //是否显示注册密码
      passwordStatus: true,
      // 密码是否明文显示
      loginPasswordStatus: true,
      // 是否显示找回密码
      isfindPassword: false,
      // 找回密码信息
      findPasswordInfo: {
        email: "",
        code: "",
        phone: "",
        password: "",
        // 下一步
        setPassword: false,
      },
      // 发送验证码倒计时
      time: 60 * 1000,
      // 是否可重新发送验证码
      codeStatus: true
    };
  },

  created() {
    // 在session storage中存储tabbar的状态
    this.$util.setSessionItem('tabbarActive', 0);
    // 在session storage中存储typeProduct的状态
    this.$util.setSessionItem('typeProductActive', 0);
    // 判断是否处于登录状态
    this.isLogin();
  },

  methods: {
    // 判断是否处于登录状态
    isLogin() {
      if(this.$cookies.get("TOKEN")) {
        // 直接进入登录界面
        this.$router.replace({name: "Home"});
      }else {
        console.log(this.$cookies.get("TOKEN"));
      }
    },

    togglePassword(key) {
      this[key] = !this[key];
    },
    
    //显示弹出层
    showPopup() {
      this.show = true;
    },

    //切换注册密码状态
    toggleRegPassword() {
      this.passwordStatus = !this.passwordStatus;
    },

    //注册
    register() {
      //表单验证
      //验证手机号
      let registerPhoneReg = /^1[3-9]\d{9}$/;
      if (!registerPhoneReg.test(this.regUserInfo.phone)) {
        //手机号验证不通过
        this.$toast("手机号错误");
        return;
      }
      //验证密码
      //支持字母数字组合, 且必须以字母开头, 6-16位
      // let registerPasswrodReg = /^[A-Za-z][A-Za-z\d]{5,15}$/;
      let registerPasswrodReg = /^[A-Za-z\d]{6,16}$/;
      if (!registerPasswrodReg.test(this.regUserInfo.password)) {
        this.$toast("密码支持字母数字组合");
        return;
      }
      //验证昵称
      //支持中英文组合, 1-10位
      let registerNickNameReg = /^[A-Za-z0-9\u4e00-\u9fa5]{1,10}$/;
      if (!registerNickNameReg.test(this.regUserInfo.nickName)) {
        this.$toast("昵称格式错误");
        return;
      }
      // 起注册请求
      this.axios({
        method: "POST",
        url: "/register",
        data: this.regUserInfo,
      })
        .then((res) => {
          // 
          this.$toast(res.data.msg);
          if (res.data.code === 100) {
            //注册成功
            this.show = false;
          }
        })
        .catch((err) => {
          
        });
    },

    //登录
    login() {
      //表单验证
      //验证手机号
      let loginPhoneReg = /^1[3-9]\d{9}$/;
      if (!loginPhoneReg.test(this.loginUserInfo.phone)) {
        //手机号验证不通过
        this.$toast("手机号错误");
        return;
      }
      //验证密码
      //支持字母数字组合, 且必须以字母开头, 6-16位
      let loginPasswrodReg = /^[A-Za-z\d]{6,16}$/;
      if (!loginPasswrodReg.test(this.loginUserInfo.password)) {
        this.$toast("密码支持字母数字组合");
        return;
      }
      // 
      //发起登录请求
      this.axios({
        method: "POST",
        url: "/login",
        data: this.loginUserInfo,
      })
        .then((res) => {
          // 
          this.$toast(res.data.msg);
          if (res.data.code === 200) {
            //登录成功
            //将token保存在cookie
            this.$cookies.set("TOKEN", res.data.token, "10d");
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({name: "Home"});
            }, 2000);
          }
        })
        .catch((err) => {
          
        });
    },

    // 先逛一逛
    goHome() {
      this.$router.replace({name: "Home"});
    },

    // 找回密码
    toggleView(status) {
      if(status == true) {
        this.codeStatus = true;
        this.findPasswordInfo.email = this.findPasswordInfo.code = '';
        this.findPasswordInfo.setPassword = false;
      }else {{
        this.loginUserInfo.phone = this.loginUserInfo.password = '';
      }}
      this.isfindPassword = status;
    },

    // 发送验证码
    sendCode() {
      if(!this.codeStatus) {
        this.$toast('重复获取验证码，请稍后再试');
        return;
      }
      if(!this.findPasswordInfo.email) {
        this.$toast('邮箱不能为空');
        return;
      }
      if(!/^\w+@[a-z0-9]+\.[a-z]{2,4}$/.test(this.findPasswordInfo.email)) {
        this.$toast('邮箱格式有误');
        return;
      }
      this.axios({
        method: "POST",
        url: "/emailValidCode",
        data: {
          email: this.findPasswordInfo.email
        }
      })
        .then((res) => {
          // 
          if(res.data.code ==  'J001') {
            this.$toast(res.data.msg);
            this.codeStatus = false;
            return;
          }
          this.$toast(res.data.msg);
        })
        .catch((err) => {
          
        });
    },

    // 重置时间
    resetTime() {
      this.time = 60 * 1000;
      this.codeStatus = true;
    },

    // 校验验证码
    checkCode() {
      if(!this.findPasswordInfo.code) {
        this.$toast('验证码不能为空');
        return;
      }
      this.axios({
        method: "POST",
        url: "/checkValidCode",
        data: {
          validCode: this.findPasswordInfo.code
        }
      })
        .then((res) => {
          
          if(res.data.code ==  'K001') {
            this.$toast('验证码正确');
            this.findPasswordInfo.setPassword = true;
          }
          if(res.data.code ==  'K002' || res.data.code ==  'K003') {
            this.$toast('验证码不正确');
          }
        })
        .catch((err) => {
          this.$toast('验证码有误');
        });
    },

    // 重置密码
    resetPassword() {
      if(!this.findPasswordInfo.phone) {
        this.$toast('手机号不能为空');
        return;
      }
      if(!this.findPasswordInfo.password) {
        this.$toast('新密码不能为空');
        return;
      }
      let loginPasswrodReg = /^[A-Za-z\d]{6,16}$/;
      if (!loginPasswrodReg.test(this.findPasswordInfo.password)) {
        this.$toast("密码支持字母数字组合");
        return;
      }
      this.axios({
        method: "POST",
        url: "/retrievePassword",
        data: {
          phone: this.findPasswordInfo.phone,
          password: this.findPasswordInfo.password
        }
      })
        .then((res) => {
          
          if(res.data.code == 'L001') {
            this.$toast(res.data.msg);
          }
          if(res.data.code ==  'L003') {
            this.$toast(res.data.msg);
          }
          if(res.data.code ==  'L004') {
            this.$toast(res.data.msg);
          }
        })
        .catch((err) => {
        });
    },

    // 返回登录页面
    goLogin() {
      this.toggleView(false);
    }
  },
};
</script>

<style lang="less" scoped>
/deep/.van-field__button {
  display: flex;
  align-items: center;
}
/deep/.van-button--primary {
  width: 78px;
  background: #ffa341;
  border-color: #ffa341;
}
/deep/.van-count-down {
  color: #fff;
  font-size: 10px;
}
/deep/.van-button__text {
  display: flex;
  align-items: center;
}
.codeTime {
  display: flex;
  align-items: center;
  color: red  ;
  font-size: 10px;
}

.login {
  color: #333;
  .reg-form {
    margin-top: 30px;
  }

  .register {
    padding: 20px 15px;
    color: #666;

    .register-title {
      font-size: 18px;
      font-weight: bold;
    }
  }

  .forgot {
    margin-top: 20px;
    display: flex;
  }

  .forgot-text {
    margin-left: auto;
    color: #ffa341;
    font-size: 14px;
  }

  .login-btn {
    margin-top: 50px;
  }

  .login-form {
    margin-top: 50px;
  }

  .welcome {
    font-size: 24px;
    font-weight: bold;
  }

  .en-welcome {
    font-size: 18px;
    color: #999;
    margin-top: 20px;
  }

  .left-nav {
    display: flex;
    align-items: center;
  }

  .logo {
    width: 36px;
    height: 36px;
    border-radius: 50%;
  }

  .logo-title {
    margin-left: 10px;
    font-size: 14px;
    font-weight: bold;
  }

  .right-title {
    color: #ffa341;
  }

  .login-box {
    position: fixed;
    top: 46px;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
  }

  .login-info {
    padding: 100px 10px 10px;
  }

  .login-title {
    margin-left: 10px;
  }
}
</style>